const service = require('./service.js');

let version = '0.0.1'
// let appid = 'wx7e320589b0acdfaf'  //广东名片APPid
 //洋务派APPid

//let unionid = 'MTcyMzA1Mw=='
// 获取用户信息
let wxGetUserInfo = function () {
  console.log('--------------------------------------------------------')
  wx.getUserInfo({
    withCredentials: true,
    success: res => {
      console.log('wx.getUserInfo接口回调：');
      console.log(res);
      shopGetUserInfo(res.encryptedData, res.iv);
    }
  })
}

// 获取商城用户信息
let shopGetUserInfo = function (encryptedData, iv) {
  let sess_key = wx.getStorageSync('idKey').session_key;
  ajax(service.url('getUserInfo'), {
    session_key: sess_key,
    encryptedData: encryptedData,
    iv: iv,
    share_user_id: wx.getStorageSync('share_user_id')
  }, function (res) {
    console.log('获取授权用户的信息')
    console.log(res)
    wx.setStorageSync('userInfo', res.data.data);

    //--获取单店的用户ID
    ajax(service.url('getConstShopUser'),{}, function(res){
      wx.setStorageSync('out_user_id', res.data.shop_user_id)
      shopGetUserShopInfo(res.data.shop_user_id);
    })
   
  })
}

// 获取单店的用户信息
let shopGetUserShopInfo = function (out_user_id) {
  ajax(service.url('getUserShopInfo'), {
    userid: out_user_id
  }, function (res) {
    wx.setStorageSync('shop_data', res.data);
  })
}

/**
 * description 对象深层合并
 * @params {Object} FirstOBJ 默认对象
 * @params {Object} SecondOBJ 需要继承的对象
 * @return {Object} 合并后的的对象
 */
let extend = (FirstOBJ, SecondOBJ) => {
  for (var key in SecondOBJ) {
    FirstOBJ[key] = FirstOBJ[key] && FirstOBJ[key].toString() === "[object Object]" ? extend(FirstOBJ[key], SecondOBJ[key]) : FirstOBJ[key] = SecondOBJ[key];
  }
  return FirstOBJ;
}

/**
 * description ajax请求
 * @params {String} url 请求地址
 * @params {Object} data 请求参数
 * @params {Function} callback 请求成功后的回调
 * @return {Void}
 */
let ajax = (url, data, callback) => {
  if (data.unionid){
    var unionid = data.unionid
  }else{
    var unionid = wx.getStorageSync('shop_data').shop_unionid
  }
  
  let token = wx.getStorageSync('shop_data').token
  let token_key = wx.getStorageSync('shop_data').token_key
  let miniproid = getApp().globalData.miniproid
  let def_data = {
    version: version,
    appid: getApp().globalData.app_id,
    unionid: unionid,
    token: token,
    token_key: token_key,
    miniproid: miniproid
  }
  let requireData = extend(def_data, data)

  wx.request({
    method: 'POST',
    url: url,
    data: requireData,
    header: {
      'Content-Type': 'application/json'
    },
    success: function (res) {
      callback(res.data)
    },
    fail: function (res) {
      // console.log(`error: ${res}`)
      console.log(res)
    }
  })
}

/**
 * description 检测手机号码是否符合规范
 * @params {String} phone 手机号码
 * @return {Boolean}
 */
let checkPhone = (phone) => {
  let reg = /^1[3|4|5|7|8][0-9]{9}$/
  return reg.test(phone)
}

//--禁用特殊字符
let hasSpecialChar = (value, msg, type) => {
  if (value != '') {
    if (type == 'id_card') {
      //--身份证验证
      var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    } else if (type == 'email') {
      //--邮箱验证
      var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    } else if (type == 'phone') {
      //--手机号验证
      var reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
    } else if (type == 'greaterZeroInteger') {
      //--正整数验证(大于0)
      var reg = /^([1-9][0-9]*){1,3}$/;
    } else if (type == 'ZeroInInteger') {
      //--非负整数验证
      var reg = /^\d+$/;
    } else if (type == 'LetterAndNumber') {
      //--英文和数字验证（不包含小数）
      var reg = /^[A-Za-z0-9]{7,15}$/;
    } else if (type == 'floatNumber') {
      //--最多有两位小数的正实数验证（包括0）
      var reg = /^[0-9]+(\.[0-9]{1,2})?$/;
    } else {
      //--禁止输入特殊符号（不包括空格）
      var reg = /^[\u4E00-\u9FA5A-Za-z0-9\s+]+$/;
    }

    if (!reg.test(value)) {
      console.log(value);
      toast(msg);
      return true;
    }
  }
}

/**
 * description 提示
 * @params {String} arg 提示内容
 * @return {Void}
 */
let toast = (arg) => {
  wx.showToast({
    title: arg,
    icon: 'none'
  })
}

/**
 * description 上传图片
 * @params {Number} size 上传上限
 * @params {String} type 'album'相册选择  'camera'拍照上传  选择方式
 * @params {Function} cb 回调函数
 * @return {Array}
 */
let upLoadImg = (size, type, cb) => {
  let arr = []
  wx.chooseImage({
    count: size,
    sizeType: ['compressed'],
    sourceType: [type],
    success: function (res) {
      var imgarr = res.tempFilePaths
      imgarr.forEach(function (item, index) {
        arr.push(item)
      })
      let imgUrl = []
      upLoad(arr, function (rel) {
        imgUrl.push(JSON.parse(rel).data)
        wx.hideLoading()
        if (imgUrl.length == imgarr.length){
          cb(imgUrl)
        }
      })
    }
  })
}
let upLoad = (img_arr, cb) => {
  wx.showLoading({
    title: '正在上传',
  })
  let uinonId = wx.getStorageSync('userInfo').shop_unionid
  for (var i = 0, len = img_arr.length; i < len; i++) {
    wx.uploadFile({
      url: service.url('fileupload'),
      filePath: img_arr[i],
      name: 'file',
      formData: {
        appid: getApp().globalData.app_id,
        unionid: uinonId,
        version: version
      },
      success: function (res) {
        cb(res.data)
      }
    })
  }
}

module.exports = {
  wxGetUserInfo: wxGetUserInfo,
  shopGetUserInfo: shopGetUserInfo,
  ajax: ajax,
  checkPhone: checkPhone,
  hasSpecialChar: hasSpecialChar,
  toast: toast,
  upLoadImg: upLoadImg
}
